#include "LoginDialog.h"
#include "adminMainWindow.h"
#include "ui_LoginDialog.h"
#include "RegisterDialog.h"
#include "DatabaseManager.h"
#include "MainWindow.h"
#include <QMessageBox>
#include <QCryptographicHash>
#include <QButtonGroup>

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog),
    m_userId(-1),       // 初始化为-1表示未登录
    m_userType("")      // 初始化为空字符串
{
    ui->setupUi(this);
    setWindowTitle("鲜花销售系统 - 登录");

    QButtonGroup *loginTypeGroup = new QButtonGroup(this);
    loginTypeGroup->addButton(ui->userLoginButton, 0);
    loginTypeGroup->addButton(ui->adminLoginButton, 1);
    ui->userLoginButton->setChecked(true);
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::on_loginButton_clicked()
{
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text();

    if(username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名和密码不能为空");
        return;
    }

    QString encryptedPassword = QString(QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Md5).toHex());

    QSqlQuery query;
    query.prepare("SELECT user_id, user_type FROM login_users WHERE username = :username AND password = :password");
    query.bindValue(":username", username);
    query.bindValue(":password", encryptedPassword);

    if(!query.exec()) {
        QMessageBox::critical(this, "错误", "数据库查询失败");
        return;
    }

    if(query.next()) {
        m_userId = query.value(0).toInt();      // 保存用户ID
        m_userType = query.value(1).toString(); // 保存用户类型

        this->accept(); // 登录成功，关闭对话框

        }
     else {
        QMessageBox::warning(this, "登录失败", "用户名或密码错误");
    }
}

void LoginDialog::on_registerButton_clicked()
{
    RegisterDialog regDialog(this);
    if(regDialog.exec() == QDialog::Accepted) {
        ui->usernameEdit->setText(regDialog.getRegisteredUsername());
        ui->passwordEdit->setFocus();
    }
}
